from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QLabel, QPushButton, QTableWidget,
                             QTableWidgetItem, QHeaderView, QComboBox, QDateEdit,
                             QHBoxLayout, QGridLayout, QFrame, QGroupBox, QMessageBox)
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtGui import QFont, QColor, QPalette
import datetime
import logging

# 使用全局样式变量
PRIMARY_COLOR = "#3498db"  # 主题蓝色
SECONDARY_COLOR = "#2ecc71"  # 绿色
ACCENT_COLOR = "#6a5acd"  # 强调色
BG_COLOR = "#f8f9fa"  # 背景色
TEXT_COLOR = "#2c3e50"  # 文字颜色

# 字体配置
HEADER_FONT = QFont("Microsoft YaHei UI", 12, QFont.Bold)
LABEL_FONT = QFont("Microsoft YaHei UI", 10)
VALUE_FONT = QFont("Microsoft YaHei UI", 10)
BUTTON_FONT = QFont("Microsoft YaHei UI", 10, QFont.Bold)
TABLE_FONT = QFont("Microsoft YaHei UI", 9)
TABLE_HEADER_FONT = QFont("Microsoft YaHei UI", 10, QFont.Bold)


class AccountSummaryTab(QWidget):
    def __init__(self, db, card_id, customer_info=None):
        super().__init__()
        self.db = db
        self.card_id = card_id
        self.customer_info = customer_info or {}
        self.logger = logging.getLogger(__name__)
        self.initUI()
        self.apply_styles()
        self.refresh_info()  # 初始加载数据

    def initUI(self):
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(15, 10, 15, 15)

        # ================= 标题区域 =================
        title_label = QLabel(f"银行系统-卡号:{self.card_id}")
        title_label.setFont(QFont("Microsoft YaHei UI", 14, QFont.Bold))
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet(f"color: {PRIMARY_COLOR};")
        main_layout.addWidget(title_label)

        # ================= 账户基本信息卡片 =================
        # 使用带边框的容器
        info_container = QFrame()
        info_container.setObjectName("infoContainer")
        info_container.setMinimumHeight(180)

        info_layout = QGridLayout(info_container)
        info_layout.setContentsMargins(15, 15, 15, 15)
        info_layout.setVerticalSpacing(15)
        info_layout.setHorizontalSpacing(20)

        # 第一行: 客户姓名和存款类型
        # 客户姓名 - 带有对比色框
        name_frame = QFrame()
        name_frame.setObjectName("nameFrame")
        name_layout = QVBoxLayout(name_frame)
        name_layout.setContentsMargins(10, 8, 10, 8)

        name_label = QLabel("客户姓名:")
        name_label.setFont(LABEL_FONT)
        name_label.setAlignment(Qt.AlignCenter)
        self.name_value = QLabel(self.customer_info.get('customerName', '未知'))
        self.name_value.setFont(VALUE_FONT)
        self.name_value.setAlignment(Qt.AlignCenter)

        name_layout.addWidget(name_label)
        name_layout.addWidget(self.name_value)
        info_layout.addWidget(name_frame, 0, 0)

        # 存款类型 - 带有对比色框
        saving_frame = QFrame()
        saving_frame.setObjectName("savingFrame")
        saving_layout = QVBoxLayout(saving_frame)
        saving_layout.setContentsMargins(10, 8, 10, 8)

        saving_label = QLabel("存款类型:")
        saving_label.setFont(LABEL_FONT)
        saving_label.setAlignment(Qt.AlignCenter)
        self.saving_value = QLabel("加载中...")
        self.saving_value.setFont(VALUE_FONT)
        self.saving_value.setAlignment(Qt.AlignCenter)

        saving_layout.addWidget(saving_label)
        saving_layout.addWidget(self.saving_value)
        info_layout.addWidget(saving_frame, 0, 1)

        # 第二行: 卡号和开户日期
        # 卡号 - 带有对比色框
        card_frame = QFrame()
        card_frame.setObjectName("cardFrame")
        card_layout = QVBoxLayout(card_frame)
        card_layout.setContentsMargins(10, 8, 10, 8)

        card_label = QLabel("卡号:")
        card_label.setFont(LABEL_FONT)
        card_label.setAlignment(Qt.AlignCenter)
        self.card_value = QLabel(self.card_id)
        self.card_value.setFont(VALUE_FONT)
        self.card_value.setAlignment(Qt.AlignCenter)

        card_layout.addWidget(card_label)
        card_layout.addWidget(self.card_value)
        info_layout.addWidget(card_frame, 1, 0)

        # 开户日期 - 带有对比色框
        open_date_frame = QFrame()
        open_date_frame.setObjectName("openDateFrame")
        open_date_layout = QVBoxLayout(open_date_frame)
        open_date_layout.setContentsMargins(10, 8, 10, 8)

        open_date_label = QLabel("开户日期:")
        open_date_label.setFont(LABEL_FONT)
        open_date_label.setAlignment(Qt.AlignCenter)
        self.open_date_value = QLabel("加载中...")
        self.open_date_value.setFont(VALUE_FONT)
        self.open_date_value.setAlignment(Qt.AlignCenter)

        open_date_layout.addWidget(open_date_label)
        open_date_layout.addWidget(self.open_date_value)
        info_layout.addWidget(open_date_frame, 1, 1)

        # 第三行: 币种和余额
        # 币种 - 带有对比色框
        currency_frame = QFrame()
        currency_frame.setObjectName("currencyFrame")
        currency_layout = QVBoxLayout(currency_frame)
        currency_layout.setContentsMargins(10, 8, 10, 8)

        currency_label = QLabel("币种:")
        currency_label.setFont(LABEL_FONT)
        currency_label.setAlignment(Qt.AlignCenter)
        self.currency_value = QLabel("加载中...")
        self.currency_value.setFont(VALUE_FONT)
        self.currency_value.setAlignment(Qt.AlignCenter)

        currency_layout.addWidget(currency_label)
        currency_layout.addWidget(self.currency_value)
        info_layout.addWidget(currency_frame, 2, 0)

        # 余额 - 突出显示
        balance_frame = QFrame()
        balance_frame.setObjectName("balanceFrame")
        balance_layout = QVBoxLayout(balance_frame)
        balance_layout.setContentsMargins(10, 8, 10, 8)

        balance_label = QLabel("当前余额:")
        balance_label.setFont(LABEL_FONT)
        balance_label.setAlignment(Qt.AlignCenter)
        self.balance_value = QLabel("¥0.00")
        self.balance_value.setFont(QFont("Microsoft YaHei UI", 12, QFont.Bold))
        self.balance_value.setAlignment(Qt.AlignCenter)

        balance_layout.addWidget(balance_label)
        balance_layout.addWidget(self.balance_value)
        info_layout.addWidget(balance_frame, 2, 1)

        # 刷新按钮
        refresh_btn = QPushButton("刷新信息")
        refresh_btn.setFont(BUTTON_FONT)
        refresh_btn.clicked.connect(self.refresh_info)
        refresh_btn.setFixedHeight(40)
        info_layout.addWidget(refresh_btn, 3, 0, 1, 2, Qt.AlignRight)

        main_layout.addWidget(info_container)

        # ================= 交易记录区域 =================
        trans_group = QGroupBox("交易记录查询")
        trans_layout = QVBoxLayout(trans_group)

        # 筛选区域
        filter_layout = QHBoxLayout()
        filter_layout.setContentsMargins(10, 10, 10, 10)

        # 交易类型筛选
        filter_layout.addWidget(QLabel("交易类型:"))
        self.type_filter = QComboBox()
        self.type_filter.addItems(["全部", "存入", "支取", "转账"])
        self.type_filter.setFont(VALUE_FONT)
        filter_layout.addWidget(self.type_filter)
        filter_layout.addStretch(1)

        # 日期范围筛选
        filter_layout.addWidget(QLabel("起始日期:"))
        self.start_date = QDateEdit()
        self.start_date.setDate(QDate.currentDate().addMonths(-1))
        self.start_date.setFont(VALUE_FONT)
        self.start_date.setCalendarPopup(True)
        self.start_date.setDisplayFormat("yyyy/MM/dd")
        filter_layout.addWidget(self.start_date)

        filter_layout.addWidget(QLabel("结束日期:"))
        self.end_date = QDateEdit()
        self.end_date.setDate(QDate.currentDate())
        self.end_date.setFont(VALUE_FONT)
        self.end_date.setCalendarPopup(True)
        self.end_date.setDisplayFormat("yyyy/MM/dd")
        filter_layout.addWidget(self.end_date)

        # 查询按钮
        search_btn = QPushButton("查询")
        search_btn.setFont(BUTTON_FONT)
        search_btn.setMinimumWidth(100)
        search_btn.setFixedHeight(40)
        search_btn.clicked.connect(self.load_transactions)
        filter_layout.addWidget(search_btn)

        trans_layout.addLayout(filter_layout)

        # 交易记录表格
        self.trans_table = QTableWidget()
        self.trans_table.setColumnCount(5)
        self.trans_table.setHorizontalHeaderLabels([
            "交易ID", "交易类型", "交易金额", "交易时间", "备注"
        ])

        # 设置表格属性
        self.trans_table.setFont(TABLE_FONT)
        self.trans_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.trans_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.trans_table.setSelectionMode(QTableWidget.SingleSelection)
        self.trans_table.setSortingEnabled(True)
        self.trans_table.verticalHeader().setVisible(False)
        self.trans_table.setAlternatingRowColors(True)

        # 设置表头
        header = self.trans_table.horizontalHeader()
        header.setFont(TABLE_HEADER_FONT)
        header.setSectionResizeMode(QHeaderView.Interactive)
        header.setDefaultSectionSize(120)
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)  # 时间列自适应
        header.setSectionResizeMode(4, QHeaderView.Stretch)  # 备注列自适应

        trans_layout.addWidget(self.trans_table)
        main_layout.addWidget(trans_group)

        self.setLayout(main_layout)

    def apply_styles(self):
        """应用样式表"""
        # 设置整体背景
        palette = self.palette()
        palette.setColor(QPalette.Background, QColor(BG_COLOR))
        self.setAutoFillBackground(True)
        self.setPalette(palette)

        # 样式表
        self.setStyleSheet(f"""
            QWidget {{
                background-color: transparent;
            }}

            #infoContainer {{
                background-color: white;
                border: 1px solid {PRIMARY_COLOR};
                border-radius: 10px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            }}

            /* 对比色框样式 */
            #nameFrame, #savingFrame, #cardFrame, #openDateFrame, #currencyFrame {{
                border: 2px solid {PRIMARY_COLOR};
                border-radius: 8px;
                background-color: rgba(52, 152, 219, 0.05);
            }}

            #balanceFrame {{
                border: 2px solid {SECONDARY_COLOR};
                border-radius: 8px;
                background-color: rgba(46, 204, 113, 0.1);
            }}

            QGroupBox {{
                border: 1px solid {PRIMARY_COLOR};
                border-radius: 8px;
                margin-top: 1em;
                padding-top: 15px;
                background-color: white;
            }}

            QGroupBox::title {{
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0px 10px;
                background-color: {PRIMARY_COLOR};
                color: white;
                border-radius: 4px;
                font-weight: bold;
                font-size: 12pt;
            }}

            QLabel {{
                color: {TEXT_COLOR};
            }}

            QTableWidget {{
                gridline-color: #e0e0e0;
                border-radius: 6px;
            }}

            QHeaderView::section {{
                background-color: {PRIMARY_COLOR};
                color: white;
                padding: 8px;
                border: none;
            }}

            QPushButton {{
                background-color: {PRIMARY_COLOR};
                color: white;
                border-radius: 6px;
                padding: 8px 16px;
            }}

            QPushButton:hover {{
                background-color: #2980b9;
            }}
        """)

    def get_account_info(self):
        """获取账户信息 - 完整实现"""
        try:
            # 获取银行卡信息和客户信息
            query = """
            SELECT 
                c.curID,
                DATE_FORMAT(c.openDate, '%Y-%m-%d') AS openDate,
                c.balance,
                c.savingID,
                u.customerName
            FROM cardinfo c
            JOIN userinfo u ON c.customerID = u.customerID
            WHERE c.cardID = %s
            """
            result = self.db.execute_query(query, (self.card_id,))

            if not result or not result[0]:
                return {
                    'balance': 0.0,
                    'currency': 'RMB',
                    'saving_type': '未知',
                    'open_date': '未知',
                    'customer_name': '未知'
                }

            card_info = result[0]

            # 获取存款类型名称
            saving_id = card_info.get('savingID', 0)
            saving_type = "未知"
            if saving_id:
                saving_query = "SELECT savingName FROM deposit WHERE savingID = %s"
                saving_result = self.db.execute_query(saving_query, (saving_id,))
                if saving_result:
                    saving_type = saving_result[0].get('savingName', '未知')

            return {
                'balance': card_info.get('balance', 0.0),
                'currency': card_info.get('curID', 'RMB'),
                'saving_type': saving_type,
                'open_date': card_info.get('openDate', '未知'),
                'customer_name': card_info.get('customerName', '未知')
            }
        except Exception as e:
            self.logger.error(f"获取账户信息失败: {str(e)}")
            return {
                'balance': 0.0,
                'currency': 'RMB',
                'saving_type': '未知',
                'open_date': '未知',
                'customer_name': '未知'
            }

    def refresh_info(self):
        """刷新账户信息"""
        account_info = self.get_account_info()

        # 确保客户信息正确更新
        self.customer_info['customerName'] = account_info['customer_name']

        # 更新UI显示
        self.name_value.setText(account_info['customer_name'])
        self.card_value.setText(self.card_id)
        self.currency_value.setText(account_info['currency'])
        self.saving_value.setText(account_info['saving_type'])
        self.open_date_value.setText(account_info['open_date'])
        self.balance_value.setText(f"¥{account_info['balance']:,.2f}")

        # 加载交易记录
        self.load_transactions()

    def load_transactions(self):
        """加载交易记录数据 """
        try:
            # 获取筛选条件
            trans_type = self.type_filter.currentText()
            start_date = self.start_date.date().toString("yyyy-MM-dd")
            end_date = self.end_date.date().addDays(1).toString("yyyy-MM-dd")  # 包含结束日期当天

            # 基础查询
            query = """
            SELECT 
                tradeID,
                tradeType,
                tradeMoney,
                tradeDate,
                remark
            FROM tradeinfo
            WHERE cardID = %s
            AND tradeDate BETWEEN %s AND %s
            """
            params = [self.card_id, start_date, end_date]

            # 添加交易类型筛选
            if trans_type != "全部":
                if trans_type == "转账":
                    query += " AND (tradeType = '转账' OR tradeType = '转账出')"
                else:
                    query += f" AND tradeType = '{trans_type}'"

            query += " ORDER BY tradeDate DESC"
            results = self.db.execute_query(query, tuple(params))

            self.render_trans_table(results or [])

        except Exception as e:
            self.logger.error(f"加载交易记录失败: {str(e)}")
            self.trans_table.setRowCount(0)
            self.trans_table.setRowCount(1)
            error_item = QTableWidgetItem(f"加载交易记录出错: {str(e)}")
            error_item.setTextAlignment(Qt.AlignCenter)
            self.trans_table.setItem(0, 0, error_item)
            self.trans_table.setSpan(0, 0, 1, 5)

    def render_trans_table(self, results):
        """渲染交易记录表格 - 确保正确显示时间"""
        self.trans_table.setRowCount(0)

        if not results:
            # 添加提示行
            self.trans_table.setRowCount(1)
            no_data_item = QTableWidgetItem("当前筛选条件下没有交易记录")
            no_data_item.setTextAlignment(Qt.AlignCenter)
            self.trans_table.setItem(0, 0, no_data_item)
            self.trans_table.setSpan(0, 0, 1, 5)
            return

        self.trans_table.setRowCount(len(results))

        for row_idx, row in enumerate(results):
            # 交易ID
            trade_id = QTableWidgetItem(str(row.get('tradeID', '')))
            trade_id.setTextAlignment(Qt.AlignCenter)
            self.trans_table.setItem(row_idx, 0, trade_id)

            # 交易类型
            trade_type = row.get('tradeType', '')
            type_item = QTableWidgetItem(trade_type)
            type_item.setTextAlignment(Qt.AlignCenter)
            self.trans_table.setItem(row_idx, 1, type_item)

            # 交易金额
            amount = float(row.get('tradeMoney', 0))
            amount_text = f"¥{amount:,.2f}"  # 格式化金额

            amount_item = QTableWidgetItem(amount_text)
            amount_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)

            # 根据交易类型设置文本颜色
            if trade_type in ["存入", "转账入"]:
                amount_item.setForeground(QColor(0, 128, 0))  # 存入为绿色
            elif trade_type in ["支取", "转账", "转账出"]:
                amount_item.setForeground(QColor(200, 0, 0))  # 支出为红色

            self.trans_table.setItem(row_idx, 2, amount_item)

            # 交易时间 - 正确格式化为日期时间字符串
            trade_date = row.get('tradeDate', None)
            if trade_date:
                # 处理多种可能的日期格式
                if isinstance(trade_date, datetime.datetime):
                    datetime_str = trade_date.strftime("%Y-%m-%d %H:%M:%S")
                elif isinstance(trade_date, str):
                    datetime_str = trade_date
                else:
                    datetime_str = str(trade_date)
            else:
                datetime_str = "未知时间"

            datetime_item = QTableWidgetItem(datetime_str)
            datetime_item.setTextAlignment(Qt.AlignCenter)
            self.trans_table.setItem(row_idx, 3, datetime_item)

            # 备注
            remark = row.get('remark', '')
            remark_item = QTableWidgetItem(remark or "None")
            self.trans_table.setItem(row_idx, 4, remark_item)

        # 调整列宽和行高
        self.trans_table.resizeColumnsToContents()
        self.trans_table.resizeRowsToContents()

        # 记录加载信息
        self.logger.info(f"成功加载 {len(results)} 条交易记录")